import serial
import json

class SerialComm:
    def __init__(self, port="/dev/ttyS1", baudrate=115200, timeout=0.01):
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.serial = None
        self.connect()

    def connect(self):
        try:
            self.serial = serial.Serial(
                port=self.port,
                baudrate=self.baudrate,
                timeout=self.timeout
            )
            if self.serial.is_open:
                print(f"串口 {self.port} 连接成功")
            else:
                print(f"串口 {self.port} 打开失败")
        except serial.SerialException as e:
            print(f"串口连接错误: {e}")

    # def send(self, data: str):
    #     """发送字符串数据（自动编码为 UTF-8）"""
    #     if self.serial and self.serial.is_open:
    #         self.serial.write(data.encode('utf-8'))

    def send(self, data: str, hex_mode: bool = False):
        """
        :param data: 如果 hex_mode=False，则当作普通字符串 UTF-8 发送；
                     如果 hex_mode=True，则把 data 当成十六进制字符串解析发送。
        """
        if not (self.serial and self.serial.is_open):
            return

        if hex_mode:
            cleaned = data.replace(" ", "").replace("0x", "")
            b = bytes.fromhex(cleaned)
        else:
            b = data.encode('utf-8')
        self.serial.write(b)
    
    def receive(self) -> str | None:
        """读取一行，并去除结尾换行符"""
        if self.serial and self.serial.is_open:
            return self.serial.readline().decode('utf-8', errors='ignore').strip()
        return None
        
    def close(self):
        if self.serial and self.serial.is_open:
            self.serial.close()
            print(f"串口 {self.port} 已关闭")

